package com.cz.basetool.ui_work.util.beep;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Vibrator;

import com.cz.basetool.R;

import java.io.IOException;

public class BeepUtil {
	private MediaPlayer mediaPlayer;
	private boolean shouldPlayBeep = true ;
	private Vibrator vibrator;
	private boolean isEmergencyPlaying = false;

	private static  BeepUtil instance = new BeepUtil();
	private BeepUtil(){
		shouldPlayBeep = true;
		isEmergencyPlaying = false;
	}
	public static BeepUtil getInstance(){
		return instance;
	}

	public void init(Context attachContext) {
		init(attachContext, R.raw.beep);
	}


	public void init(Context attachContext, int rawId) {
		vibrator = (Vibrator)attachContext.getSystemService(Context.VIBRATOR_SERVICE);
//
//
//		attachContext.setVolumeControlStream(AudioManager.STREAM_MUSIC);

		AudioManager audioService = (AudioManager) attachContext
				.getSystemService(Context.AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			shouldPlayBeep = false;
		}

		mediaPlayer = new MediaPlayer();
		if(mediaPlayer != null){
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			// 　　注册事件。当播放完毕一次后，重新指向流文件的开头，以准备下次播放。
			// 复制代码 代码如下:
		}

		if(mediaPlayer != null){
			// When the beep has finished playing, rewind to queue up another one.
			mediaPlayer
					.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
						@Override
						public void onCompletion(MediaPlayer player) {
							player.seekTo(0);
							vibrator.cancel();
						}
					});
		}


		AssetFileDescriptor file = attachContext.getResources()
				.openRawResourceFd(rawId);
		try {
			if(mediaPlayer != null){
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
			}

			file.close();
			if(mediaPlayer != null){
				mediaPlayer.setVolume(1.0f,1.0f);
			}
			if(mediaPlayer != null){
				mediaPlayer.prepare();
			}
		} catch (IOException ioe) {
			mediaPlayer = null;
		}
	}


	public void playSound() {
		playSound(2000,0);
	}


	public void playSound( long period, int repeate) {
		if (shouldPlayBeep && mediaPlayer != null) {
			vibrator.vibrate(new long[]{0,period},repeate);
			mediaPlayer.start();
		}
	}

	public void playSoundEmergency(){
		if(isEmergencyPlaying == false){
			isEmergencyPlaying = true;
			if(mediaPlayer != null){
				mediaPlayer.setLooping(true);
			}
			playSound(500,1);
		}
	}


	public void cancel(){
		if(mediaPlayer != null){
			mediaPlayer.setLooping(false);
		}

		isEmergencyPlaying = false;

		if(vibrator != null){
			vibrator.cancel();

		}
	}


	public void release(){
		cancel();
		if(mediaPlayer != null){
			mediaPlayer.release();
			mediaPlayer = null;
		}
	}
}
